<template>
  <ZwSearchForm row-num="4" :option="searchOption" @search="search" @reset="reset" ref="searchRef" />
  <ZwTable ref="tableRef" class="table-box" @select="onSelect" @select-all="onSelectAll" :option="tableOption" :fetch-params="state.searchParams" :fetch-api="fetch()">
    <template #headerOperateLeft>
      <div style="display: flex; align-items: center">
        <div style="font-size: 13px; line-height: 1; margin-right: 10px">最近同步时间：</div>
        <div style="display: flex; align-items: center">
          <el-dropdown style="margin-left: 10px">
            <span style="color: #ff6b00; font-size: 12px; cursor: pointer; line-height: 1; padding-right: 6px">
              同步企微客户<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item> 直接同步 </el-dropdown-item>
                <el-dropdown-item> 高级同步</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </template>
    <template #headerOperate>
      <el-button>协助人审核</el-button>
      <el-dropdown style="margin-left: 10px">
        <el-button type="primary">
          批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="1" v-auth="'BATCH_MARK'"> 批量打标 </el-dropdown-item>
            <el-dropdown-item command="2" v-auth="'BATCH_ASSIGN'"> 批量分配 </el-dropdown-item>
            <el-dropdown-item command="3" v-auth="'EXPORT_CUSTOMER'"> 导出客户</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </template>
  </ZwTable>
  <ZWDepart ref="DepartRef" v-show="showDepart" @submit="getZWDepartData" :isLocal="true" />
  <ImportCustomer ref="ImportCustomerRef" :multiple="false" @save="getListFun" @cancel="closeImportCustomer" />
  <BatchLabel ref="BatchLabelRef" @save="getTagsFun" />
  <AddFollow ref="AddFollowRef" @save="getListFun" />
  <GroupChart ref="GroupChartRef" @submit="getGroupFun" />
</template>
<script lang="tsx" setup>
  import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
  import { ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import ZwTable from '@/components/zw/table/Table'
  import { deepCopy } from '@/utils/helper'
  import { dividerProps, ElButton, ElMessage, ElPopover, ElProgress } from 'element-plus'
  import { getCenterCustomerList } from '@/api/customerCenter'
  import GroupChart from '@/components/chart/GroupChart.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import ImportCustomer from './ImportCustomer.vue'
  import BatchLabel from '@/components/BatchLabel.vue'
  import AddFollow from './AddFollow.vue'
  import { getAssistantNum } from '@/api/customer/manage/list'
  import { useRouter } from 'vue-router'
  import { useStore } from '@/store'
  import { getSetionId, tableH, reSize } from '@/utils/utils'
  import { stageList, sourceList } from '../../configure/api'
  const searchRef = ref(null)
  const tableRef = ref(null)
  const CustomerListSearchRef = ref<any>(null)
  const router = useRouter()
  const tabsList = ref([]) //当前选中的标签的展示数组
  const store = useStore()
  const DepartRef = ref(null)
  const tabH = ref(400)
  const formRef = ref<InstanceType<typeof ElForm>>()
  const ImportCustomerRef = ref(null)
  const BatchLabelRef = ref(null)
  const PaginationRef = ref<any>(null)
  const AddFollowRef = ref(null)
  const GroupChartRef = ref({})
  const showDepart = ref(true)
  const creators = ref([])
  const stageListOptList = ref([]) //客户阶段字典
  const assistantNum = ref(0)
  const sourceArr = ref([]) // 来源字典
  const groupOptions = ref([])
  let updateTime = ref('')
  let tableData = ref([])
  const chooseTableData = ref([]) //当前选中的表格的数据
  const defaultParams = reactive({
    status: '',
    name: '',
    type: '',
    effect_time: [],
    work_user_list: [],
    task_status: ''
  })
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  let departTypeObj: any = {
    departType: '', //当前打卡选择员工的类型
    departData: [], //选中的数据
    itemData: '' //当前传入的数据
  }
  const search = () => {}
  const reset = () => {}
  const searchOption = computed(() => {
    return [
      {
        label: '客户信息',
        name: 'mobile_or_name',
        value: '',
        type: 'input',
        placeholder: '请输入客户手机号|姓名|昵称搜索'
      },
      {
        label: '客户来源',
        name: 'source_id',
        value: '',
        type: 'select',
        placeholder: '请选择客户来源',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            const params = { page: 1, page_size: 99999 }
            sourceList(params).then((res: any) => {
              let sourceArr: any = []
              res.data.forEach((item: any) => {
                sourceArr.push(item)
              })
              resolve(sourceArr)
            })
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '客户阶段',
        name: 'stage',
        value: '',
        type: 'select',
        placeholder: '请选择客户阶段',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            const params = { page: 1, page_size: 99999 }
            stageList(params).then((res: any) => {
              let stageArr: any = []
              res.forEach((item: any) => {
                stageArr.push(item)
              })
              resolve(stageArr)
            })
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '客户保护',
        name: 'protect',
        value: '',
        type: 'select',
        placeholder: '请选择是否为客户保护',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve([
              {
                name: '所有',
                id: 0
              },
              {
                name: '未保护',
                id: 1
              },
              {
                name: '已保护',
                id: 2
              }
            ])
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '归属员工',
        name: 'work_user_list',
        value: [],
        type: 'select',
        placeholder: '请选择归属员工',
        multiple: true,
        popperClass: 'zw-hide_select_option',
        isUserSelect: true,
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '触达方式',
        name: 'touch_mode',
        value: '',
        type: 'select',
        placeholder: '请选择触达方式',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve([
              {
                name: '全部',
                id: -1
              },
              {
                name: '手机',
                id: 1
              },
              {
                name: '短信',
                id: 2
              },
              {
                name: '企业微信',
                id: 3
              },
              {
                name: '微信',
                id: 4
              },
              {
                name: '抖音',
                id: 5
              },
              {
                name: '公众号',
                id: 6
              },
              {
                name: '邮箱',
                id: 7
              }
            ])
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '客户标签',
        name: 'work_user_list',
        value: [],
        type: 'select',
        placeholder: '请选择客户标签',
        multiple: true,
        popperClass: 'zw-hide_select_option',
        isTagSelect: true,
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '客户状态',
        name: 'cust_status',
        value: '',
        type: 'select',
        placeholder: '请选择客户状态',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve([
              {
                name: '全部',
                id: -1
              },
              {
                name: '已流失',
                id: 1
              },
              {
                name: '正常',
                id: 2
              },
              {
                name: '异常',
                id: 3
              }
            ])
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '所在企微群',
        name: 'group _cha',
        value: '',
        type: 'select',
        placeholder: '请选择所在企微群',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve([
              {
                name: '全部',
                id: -1
              },
              {
                name: '已完成',
                id: 1
              },
              {
                name: '未完成',
                id: 2
              },
              {
                name: '超时完成',
                id: 3
              },
              {
                name: '超时未完成',
                id: 4
              }
            ])
          })
        },
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '创建时间',
        name: 'created_time',
        value: [],
        type: 'datePicker',
        datePickerType: 'daterange',
        datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期'
      },
      {
        label: '添加时间',
        name: 'follow_time',
        value: [],
        type: 'datePicker',
        datePickerType: 'daterange',
        datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期'
      }
    ]
  })
  const tableOption = [
    {
      prop: 'name',
      label: '客户信息',
      width: 250
    },
    {
      prop: 'name',
      label: '手机号',
      width: 250
    },
    {
      prop: 'name',
      label: '客户标签',
      width: 250
    },
    {
      prop: 'name',
      label: '可联系员工',
      width: 250
    },
    {
      prop: 'name',
      label: '客户来源',
      width: 250
    },
    {
      prop: 'name',
      label: '客户阶段',
      width: 250
    },
    {
      prop: 'name',
      label: '添加时间',
      width: 250
    },
    {
      prop: 'name',
      label: '创建时间',
      width: 250
    }
  ]
  const fetch = () => {
    return getCenterCustomerList
  }
  // 表格的自适应高度
  const getTableH = () => {
    tabH.value = tableH('.table-box')
  }
  // 获取群聊
  const getGroupFun = (val: any) => {
    console.log(val, 555)
    groupOptions.value = [val]
    CustomerListSearchRef.value.formData.group_chat = [val.group_id]
  }
  // 选中表格 checkbox
  const onSelect = (selection: any, row: any) => {
    chooseTableData.value = selection
  }
  // 全选
  const onSelectAll = (selection: any) => {
    chooseTableData.value = selection
  }
  const getListFun = () => {}
  // 获取最新同步时间
  const getSyncTimeFun = () => {
    // getSyncTime({ sync_type: 120 }).then((r: any) => {
    //   updateTime.value = r.weiwork_synctime
    // })
  }
  getSyncTimeFun()

  // 添加跟进
  const showAddFollowFun = (val: any) => {
    if (!val.id) {
      ElMessage.error('当前数据异常,请稍后再试')
      getListFun()
      return
    }
    AddFollowRef.value.followId = val.id
    AddFollowRef.value.drawerData.userInfo = val
    AddFollowRef.value.drawerData.show = true
  }
  // 导出客户数据
  const exportCustomerFun = () => {
    let arr = chooseTableData.value.map((it: any) => {
      return it.id
    })
    exportCustomer({ cust_Ids: arr.toString() })
      .then((r: any) => {
        if (r.file_url) {
          window.location = r.file_url
        }
      })
      .catch((e: object) => {
        console.log(e, 555)
      })
  }
  let timeId: any = ''
  let loading: any = ''
  const checkSuccessSync = (jobid: string) => {
    custSyncResult({ jobid, type: 1 }).then((r: any) => {
      loading = ElLoading.service({
        lock: false,
        text: '同步中....',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (!r) {
        loading.close()
        timeId = ''
        ElMessage.error('同步失败')
        return
      }
      if (r.status > 1) {
        loading.close()
        clearInterval(timeId)
        getSyncTimeFun()
        getListFun()
        timeId = ''
        ElMessage[r.status == 2 ? 'success' : 'error'](r.status == 2 ? '同步成功' : '同步失败')
      } else {
        if (!timeId) {
          timeId = setInterval(() => {
            checkSuccessSync(jobid)
          }, 3000)
        }
        if (CustomerListSearchRef.value.formData.created_at.length > 0) {
          CustomerListSearchRef.value.formData.created_time = CustomerListSearchRef.value.formData.created_at[0] + '~' + CustomerListSearchRef.value.formData.created_at[1]
        }
      }
    })
  }
  // 同步企业微信
  const synchronizationFun = async () => {
    const res = await custSync()
    checkSuccessSync(res.jobid)
  }

  // 批量分配员工
  const batchAssignStaffFun = (isAll: boolean) => {
    let customer_list = isAll
      ? chooseTableData.value.map((it) => {
          return it.id
        })
      : [departTypeObj.itemData.id]
    let work_user_list = departTypeObj.departData.map((it) => {
      return it.id
    })
    work_user_list = departTypeObj.departType == 'one' ? [work_user_list[work_user_list.length - 1]] : work_user_list
    batchAssignStaff({ customer_list, work_user_list })
      .then((r: object) => {
        CustomerListSearchRef.value.formData.work_user_ids = []
        getListFun()
      })
      .catch((e: object) => {
        console.log(e, 555)
      })
  }

  // 关闭导入的弹框
  const closeImportCustomer = () => {
    showDepart.value = true
  }

  let labelObj: any = {
    type: '', //当前打开选择标签是哪个类型
    data: [] //选中标签的数据存储
  }
  //切换标签
  const changeLabel = (value: any, al: any) => {
    tabsList.value = tabsList.value.filter((item: any) => {
      return value.includes(item.id)
    })
  }
  // 打开选择标签弹框
  const openBatchLabel = (type: string, num?: number) => {
    labelObj.type = type
    labelObj.labelType = num
    BatchLabelRef.value.dialogData.delname = '不移除'
    BatchLabelRef.value.title = '选择客户标签'
    BatchLabelRef.value.dialogData.labelChooseType = type == 'formData' ? 2 : 1
    BatchLabelRef.value.chooseDataArr = []
    if (tabsList.value.length > 0 && type == 'formData') {
      BatchLabelRef.value.chooseDataArr = tabsList.value
    }
    BatchLabelRef.value.dialogVisible = true
  }

  const getTagType = (val: number) => {
    switch (val) {
      case 0:
        return 3
      case 1:
        return 1
      case 2:
        return 2
    }
  }
  // 获取当前选中的标签
  const getTagsFun = async (val?: any) => {
    if (labelObj.type == 'formData') {
      CustomerListSearchRef.value.formData.tag_ids = val?.idList
      //  0: 无标签，1：满足任意一个标签， 2：同时满足所有标签
      CustomerListSearchRef.value.formData.select_tag_type = getTagType(val.labelType)
      tabsList.value = val.data
      return
    }
    let param = {
      customer_list: getSetionId('id', chooseTableData.value),
      tag_list: val.idList
    }
    //  3批量打标签  4 批量删除标签
    const res = val.labelType == 3 ? await batchAddTag(param) : await batchRmTag(param)
    ElMessage.success(`批量${val.labelType == 3 ? '打' : '移除'}标签成功！`)
    getListFun()
  }

  // 当前分页改变
  const pageChangeFun = (val: object) => {
    CustomerListSearchRef.value.formData.page = val.page
    CustomerListSearchRef.value.formData.page_size = val.page_size || CustomerListSearchRef.value.formData.page_size
    getListFun()
  }

  // 获取当前选中的客户
  const handleSelectionChange = (val: any) => {
    chooseTableData.value = val
  }

  //打开新建选择人
  const openDepart = (type: string, data: any) => {
    departTypeObj.departType = type
    if (type != 'formData') {
      departTypeObj.departData = []
    }
    if (data) {
      departTypeObj.itemData = data
      // 未分配
      if (data.cust_assign_status == 0) {
        DepartRef.value.selectedMember = []
      }
      if (data.cust_assign_status == 1) {
        // 客户转交
        DepartRef.value.disabledSelected = [data.cust_distribution?.work_user?.id]
        DepartRef.value.selectedMember =
          data.distribution_work_userid != 0
            ? [
                {
                  name: data.assign_employees,
                  id: data.distribution_work_userid,
                  type: 'user'
                }
              ]
            : []
      }

      DepartRef.value.multiple = false
    } else {
      departTypeObj.itemData = {}
      DepartRef.value.multiple = true
      DepartRef.value.selectedMember = []
    }
    DepartRef.value.departVisble = true
    DepartRef.value.title = '选择员工'
  }
  // 获取当前选中的员工的数据
  const getZWDepartData = (val?: any, flag?: boolean) => {
    if (flag) return
    creators.value = val
    CustomerListSearchRef.value.formData.work_user_ids = getSetionId('id', val)
    if (creators.value.length == 0) {
      ElMessage.warning('请选择员工')
      return
    }
    if (departTypeObj.departType != 'formData') {
      departTypeObj.departData = val
      batchAssignStaffFun(departTypeObj.departType != 'one')
    }
  }
  const changeDepart = (data: any) => {
    creators.value = creators.value.filter((item: any) => data.includes(item.id))
    CustomerListSearchRef.value.formData.work_user_ids = getSetionId('id', creators.value)
  }
  // 前往详情页
  const toDetail = (val: any) => {
    if (!val.id) {
      ElMessage.error('当前数据异常，请刷新页面')
      return
    }
    router.push(`/customer/manage/list/detail?id=${val.id}&type=${val.type}`)
  }
  const onBatch = (command: string) => {
    command == '1' && openBatchLabel('batch', 3)
    command == '2' && openDepart('batch', '')
    command == '3' && exportCustomerFun()
  }
  onMounted(() => {
    getAssistantNum().then((res: any) => {
      console.log('协助审核人上标', res)
      assistantNum.value = res.num
    })
    getTableH()
    reSize(getTableH)
  })
</script>
<style lang="scss" scoped>
  .control-btn-box {
    width: 80vw;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0px 16px 10px;
    .left {
      display: flex;
      .sync_hronize {
        display: flex;
        align-items: center;
        margin-right: 10px;
        color: #ff6b00;
        cursor: pointer;
      }
      .select-box {
        padding: 0 12px;
        border: 1px solid #eaeaea;
        background: #f9f9f9;
        border-radius: 1px;
        margin-right: 28px;

        .el-input__inner {
          border: none;
        }
      }

      span {
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #33302d;
        line-height: 44px;
      }
    }
    .right {
      display: flex;
      .audit {
        position: relative;
        margin-right: 10px;
        .audit_num {
          width: 16px;
          height: 16px;
          line-height: 16px;
          font-size: 10px;
          color: #fff;
          text-align: center;
          background: #ff6b00;
          border-radius: 9px;
          border: 1px solid #ff6b00;
          position: absolute;
          right: 3px;
          top: 3px;
        }
      }
    }
  }
</style>
